package com.powerbank.user.service.impl;

import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powerbank.common.entity.User;
import com.powerbank.common.entity.UserIdentity;
import com.powerbank.common.exception.BusinessException;
import com.powerbank.common.result.ResultCode;
import com.powerbank.user.dto.IdentityVerifyDTO;
import com.powerbank.user.mapper.UserIdentityMapper;
import com.powerbank.user.mapper.UserMapper;
import com.powerbank.user.service.IdentityVerifyService;
import com.powerbank.user.vo.IdentityVerifyVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 实名认证服务实现类
 */
@Slf4j
@Service
public class IdentityVerifyServiceImpl implements IdentityVerifyService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserIdentityMapper userIdentityMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IdentityVerifyVO submitIdentityVerify(Long userId, IdentityVerifyDTO verifyDTO) {
        // 验证用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }

        // 检查是否已经提交过认证
        LambdaQueryWrapper<UserIdentity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserIdentity::getUserId, userId);
        UserIdentity existingIdentity = userIdentityMapper.selectOne(wrapper);

        if (existingIdentity != null) {
            if (existingIdentity.getVerifyStatus() == 1) {
                throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "您已通过实名认证，无需重复提交");
            } else if (existingIdentity.getVerifyStatus() == 0) {
                throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "您的认证申请正在审核中，请耐心等待");
            }
            // 如果是认证失败状态(2)，则可以重新提交
        }

        // 检查身份证号是否已被其他用户使用
        LambdaQueryWrapper<UserIdentity> idCardWrapper = new LambdaQueryWrapper<>();
        idCardWrapper.eq(UserIdentity::getIdCardNo, verifyDTO.getIdCardNo())
                .ne(UserIdentity::getUserId, userId);
        if (userIdentityMapper.selectCount(idCardWrapper) > 0) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "该身份证号已被其他用户使用");
        }

        UserIdentity userIdentity;
        if (existingIdentity != null) {
            // 更新现有记录
            userIdentity = existingIdentity;
            BeanUtils.copyProperties(verifyDTO, userIdentity);
            userIdentity.setVerifyStatus(0); // 重新设为待审核
            userIdentity.setVerifyTime(null);
            userIdentity.setRejectReason(null);
            userIdentity.setUpdatedTime(LocalDateTime.now());
            userIdentityMapper.updateById(userIdentity);
        } else {
            // 创建新记录
            userIdentity = new UserIdentity();
            BeanUtils.copyProperties(verifyDTO, userIdentity);
            userIdentity.setUserId(userId);
            userIdentity.setVerifyStatus(0); // 待审核
            userIdentity.setVerifyLevel(2); // 中级认证
            userIdentity.setCreatedTime(LocalDateTime.now());
            userIdentity.setUpdatedTime(LocalDateTime.now());
            userIdentityMapper.insert(userIdentity);
        }

        return buildIdentityVerifyVO(userIdentity);
    }

    @Override
    public IdentityVerifyVO getIdentityVerifyInfo(Long userId) {
        LambdaQueryWrapper<UserIdentity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserIdentity::getUserId, userId);
        UserIdentity userIdentity = userIdentityMapper.selectOne(wrapper);

        if (userIdentity == null) {
            return null;
        }

        return buildIdentityVerifyVO(userIdentity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IdentityVerifyVO resubmitIdentityVerify(Long userId, IdentityVerifyDTO verifyDTO) {
        // 查找现有认证记录
        LambdaQueryWrapper<UserIdentity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserIdentity::getUserId, userId);
        UserIdentity existingIdentity = userIdentityMapper.selectOne(wrapper);

        if (existingIdentity == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "未找到认证记录");
        }

        if (existingIdentity.getVerifyStatus() != 2) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "只有认证失败的记录才能重新提交");
        }

        // 检查身份证号是否已被其他用户使用（排除当前用户）
        LambdaQueryWrapper<UserIdentity> idCardWrapper = new LambdaQueryWrapper<>();
        idCardWrapper.eq(UserIdentity::getIdCardNo, verifyDTO.getIdCardNo())
                .ne(UserIdentity::getUserId, userId);
        if (userIdentityMapper.selectCount(idCardWrapper) > 0) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "该身份证号已被其他用户使用");
        }

        // 更新认证信息
        BeanUtils.copyProperties(verifyDTO, existingIdentity);
        existingIdentity.setVerifyStatus(0); // 重新设为待审核
        existingIdentity.setVerifyTime(null);
        existingIdentity.setRejectReason(null);
        existingIdentity.setUpdatedTime(LocalDateTime.now());

        userIdentityMapper.updateById(existingIdentity);

        return buildIdentityVerifyVO(existingIdentity);
    }

    /**
     * 构建认证信息VO
     */
    private IdentityVerifyVO buildIdentityVerifyVO(UserIdentity userIdentity) {
        IdentityVerifyVO vo = new IdentityVerifyVO();
        BeanUtils.copyProperties(userIdentity, vo);

        // 敏感信息脱敏
        vo.setRealName(DesensitizedUtil.chineseName(userIdentity.getRealName()));
        vo.setIdCardNo(DesensitizedUtil.idCardNum(userIdentity.getIdCardNo(), 4, 4));

        // 设置认证权益描述
        vo.setBenefits(getVerifyBenefits(userIdentity.getVerifyLevel(), userIdentity.getVerifyStatus()));

        return vo;
    }

    /**
     * 获取认证权益描述
     */
    private String getVerifyBenefits(Integer verifyLevel, Integer verifyStatus) {
        if (verifyStatus != 1) {
            return "完成实名认证后可享受相关权益";
        }

        StringBuilder benefits = new StringBuilder();
        switch (verifyLevel) {
            case 2: // 中级认证
                benefits.append("• 免押金租借充电宝\n");
                benefits.append("• 更高的租借额度\n");
                benefits.append("• 优先客服服务\n");
                benefits.append("• 专属优惠活动");
                break;
            case 3: // 高级认证
                benefits.append("• 免押金租借充电宝\n");
                benefits.append("• 最高租借额度\n");
                benefits.append("• VIP客服通道\n");
                benefits.append("• 专属VIP优惠\n");
                benefits.append("• 优先新功能体验");
                break;
            default:
                benefits.append("• 基础认证权益");
        }

        return benefits.toString();
    }
}